/*
 * @Date: 2023-04-13 17:03:20
 * @LastEditors: Dannycjh 2233879049@qq.com
 * @LastEditTime: 2023-04-28 10:18:42
 */
import { _decorator, Component, find, instantiate, Node, NodePool, Prefab, resources } from 'cc';
import { App } from '../App';
import { Singleton } from '../common/Common';
import UtilTool from './UtilTool';
const { ccclass, property } = _decorator;

/**
 * 预制体基类
 * 
 * 传入预制体名字和对应的属性参数（可不传）
 */
@ccclass('PrefabBase')
export class PoolManager extends Singleton<PoolManager> {
    public dictPool: {} = {}

    /**
     * 初始化对象池
     * @param count 生成的数量
     * @param prefab 生成为节点的预制体
     */
    public initPool(name: string, count = 1, isSuffix:boolean = false) {
        //如果本身有预制体不再生成，用于重复进入游戏场景
        if (this.dictPool[name]) {
            UtilTool.printLog('不再生成 ' + name);
            
            return;
        }else{
            let pool = new NodePool();
            this.dictPool[name] = pool;
            UtilTool.printLog('生成:' + name);
            
        }

        let paths = 'prefabs/'
        if (isSuffix) {
            paths = 'prefabs/' + App.language.getLanguageSuffix2()
        }
        
        resources.load(paths + `${name}`, Prefab, (err, prefab) => {
            if (err) {
                UtilTool.printLog("*********************预制体为空");
            } else {
                for (let index = 0; index < count; index++) {
                    let node: Node = instantiate(prefab);
                    this.setNode(node);
                }
                /*  const CanvasNode = find('Canvas');
                 const node: Node = instantiate(prefab);
                 let script = node.getComponent(name)
                 for (const key in args) {
                     script[key] = args[key];
                 }
                 CanvasNode.addChild(node) */
            }
        })
    }

    /**
     * 获取节点
     * @param prefab 生成为节点的预制体或名字
     * @param parent 该节点的父节点
     * @param args   该节点对应脚本的参数
     * @returns 生成或者对象池中的节点
     */
    public getNode(prefab: any, parent?: Node, args?: any) {
        UtilTool.printLog(this.dictPool,'当前缓存的对象池');
        UtilTool.printLog('我要生成的prefab：',prefab);
        
        
        if (!prefab) return;
        let name = ''
        if (typeof prefab == "string") {
            name = prefab
        } else {
            name = prefab.name;
        }
        let node: Node = null;
        let pool = this.dictPool[name];

        if (pool && pool.size() > 0) {
            node = pool.get();
        } else {
            if (typeof prefab == "string") {
                return
            }
            node = instantiate(prefab);
        }
        /* let script = node.getComponent(name)
        for (const key in args) {
            script[key] = args[key];
        } */
        node.parent = parent;
        node.active = true; 
        return node;
    }

    /**
 * 回收节点
 * @param node 回收的节点
 */
    public setNode(node: Node) {
        const name = node.name;
        let pool = null;
        if (this.dictPool[name]) {
            pool = this.dictPool[name];
        }
        else {
            UtilTool.printLog('回收时找不到name');
            pool = new NodePool();
            this.dictPool[name] = pool;
        }
        if (pool.size() > 100) {
            node.destroy();
            return;
        }
        pool.put(node);
    }

    public get getNodePool() {
        return this.dictPool
    }

    public clear() {
        // UtilTool.printLog(this.dictPool[name]);
        // UtilTool.printLog(this.dictPool[name]?._pool.length);
        // this.dictPool[name]?._pool.length && (this.dictPool[name]._pool.length = 0)

        //让预制体引用清空
        
        Object.values(this.dictPool).forEach((item:NodePool) =>{
            // assetManager.releaseAsset(item);
            item.clear()
        })
        this.dictPool = {};
    }

    //     /**
    //   * 清空对象池
    //   */
    //     clean(node) {
    //         /*  if (pool) {
    //              pool.clear();
    //              // log(`BasePool Tip: 清空${this.MemberFlag}Pool成功,当前池容量:${this._pool.size()}`);
    //          } */
    //         const name = node.name;
    //         this.dictPool?.[name] && this.dictPool[name].clear()
    //         UtilTool.printLog(this.dictPool);

    //         /*  //释放预制体组件资源
    //          if (this._prefab) {
    //              this._prefab.decRef();
    //              this._prefab = null;
    //              // log(`BasePool Tip: 释放${this.MemberFlag}Pool 资源数据`);
    //          } */
    //     }
}

